/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package hu.bme.j2ee.v37zen.beans;

import com.google.gson.Gson;
import hu.bme.j2ee.v37zen.entities.User;
import hu.bme.j2ee.v37zen.util.PasswordDigest;
import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author Kiss Dániel
 */
@Stateless
@LocalBean
public class ExporterBean {

    @EJB
    FindUsersBean fub;
    @PersistenceContext
    EntityManager em;
    
    public String export(String username, String password){
        if( username == null || password == null || username.isEmpty() || password.isEmpty() ){
            return "";
        }
        password = PasswordDigest.encodePasswordUnsafe(password);
        em.flush();
        User user = fub.findUserByUsernameEager(username);
        if(user != null && !user.getPassword().equals(password)){
            return "{\"Exception\":{\"Message\":\"Authentication error!\"}}";
        }
        
        String export = this.generateJSON(user);
        
        return export;
    }
    
    public String localExport(String username){
        if(username == null){
            return "";
        }
        em.flush();
        User user = fub.findUserByUsernameEager(username);
        
        return generateJSON(user);
    }

    private String generateJSON(User user){
        
        Gson gson = new Gson(); 
        
        return gson.toJson(user.getDials());
    }
}
